package java6699.lesson09;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;

import java.io.*;

/**
 * @program: java_zzx
 * @description:
 * @author: zzx
 * @create: 2022-10-31 20:15
 **/
public class ReadFile6699Controller {
    @FXML
    public TextField tfFilename;
    @FXML
    public TextArea taText;

    @FXML
    public void readFile(ActionEvent actionEvent) {
        taText.clear();//清空
        // 步骤1：确定输入的源文件，并确保源文件已经存在
        String name = tfFilename.getText().trim();
        if (name.isEmpty()) {
            alert("文件名不能为空！");
            tfFilename.selectAll();
            tfFilename.requestFocus();
            return;
        }
        //步骤2：创建指向文件的带缓冲的字符输入流
        File file = new File(name);
        StringBuilder sb = new StringBuilder();
        //步骤4：关闭资源：请使用JDK1.7提供的ARM块自动关闭资源,br自动关闭
        try (BufferedReader br = new BufferedReader(new FileReader(file))){
            String line;
            //步骤3：循环读数据，每次读一行
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } catch (FileNotFoundException e) {
            alert(file.getAbsolutePath() + "文件不存在！");
            tfFilename.selectAll();
            tfFilename.requestFocus();
            e.printStackTrace();
        } catch (IOException e) {
            alert(e.getMessage());
            e.printStackTrace();
        }
        //步骤5：将读到的数据显示在多行文本框中
        taText.appendText(sb.toString());
    }

    public void alert(String msg) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("读文本文件|字符缓冲流");
        alert.setHeaderText("请注意!");
        alert.setContentText(msg);
        alert.show();
    }
}
